const {Controller} = require("ee-core");
const {MUtils} = require("../utils/MUtils");
const Services = require("ee-core/services");
const {USER_AGENT} = require("../constant/constant");
const Addon = require("ee-core/addon");
const {AccountResp} = require("../model/AccountResp");
const {PbContext} = require("../context/PbContext");
const {ConfigContext} = require("../context/ConfigContext");
const {LockUtil} = require("../utils/LockUtil");
const CoreWindow = require("ee-core/electron/window");
const Log = require('ee-core/log');
const {chromium} = require('playwright')


class PbController extends Controller {
    constructor(ctx) {
        super(ctx);
    }

    async createPbWindow() {

        if (PbContext.pbWin != null) {
            PbContext.pbWin.destroy();
        }

        console.log('ConfigContext.globConfig.pbUrl: ', ConfigContext.globConfig.pbUrl);
        let opt = {
            title: PbContext.windowsObj.windowTitle,
            width: 1000,
            height: 300,
            frame: true,
            x: 0,
            y: 600,
            webPreferences: {
                webSecurity: true,
                nodeIntegration: false,
                contextIsolation: false,
                userAgent: USER_AGENT,
                backgroundColor: '#000000',
            }

        }
        const win = Addon.get('window').create(PbContext.windowsObj.windowName, opt);
        PbContext.pbWinId = win.webContents.id;
        // load page
        win.loadURL(ConfigContext.globConfig.pbUrl, {userAgent: USER_AGENT}).then();

        win.on('closed', () => {
            PbContext.pbWin = null
        });
        // 监听过滤器
        const lockKey = `account_lock_getAccount`;
        win.webContents.session.webRequest.onBeforeSendHeaders(async (details, callback) => {
            // 获取请求路径
            const targetUrl = details.url;
            // 获取请求头
            const targetHeader = details.requestHeaders;
            // 强制设置请求头的User_Agent
            details.requestHeaders['User-Agent'] = USER_AGENT;
            // 根据平台处理拦截
            if (targetUrl != null
                && targetUrl.indexOf("/account-balance") > 0
                && targetHeader != null) {
                const cookie = targetHeader['Cookie'];
                const host = getHost(targetUrl);
                const userAgent = targetHeader['User-Agent'];
                const referer = targetHeader['Referer'];
                if (host != null && cookie != null) {
                    // 刷新平博session上下文信息,用于后续平博的接口调用
                    PbContext.refreshHeaderContext({
                        "Accept": "application/json, text/plain, */*",
                        "Cookie": cookie,
                        "User-Agent": userAgent,
                        "Referer": referer,
                        "Host": host,
                    })

                    const b = LockUtil.lock(lockKey);
                    if (!b) {
                        throw new ReferenceError("获取平博账户正在处理中，请勿重复操作！");
                    }
                    // 获取账号数据
                    try {
                        // 请求接口刷新上下文
                        setTimeout(() => {
                            Services.get("pb").getAccount().then((result) => {
                                // 向前端发送数据
                                CoreWindow.getMainWindow().webContents.send("pb_user_context_chanel", PbContext.userContext);
                            }).catch(err => {
                                console.error(err)
                            })
                        }, 2000)
                    } finally {

                    }
                }
            }

            // 放行请求
            callback({cancel: false, requestHeaders: details.requestHeaders});
        });


        // 监听 new-window-for-tab 事件
        win.webContents.on('did-start-loading', (event, url, frameName, disposition, options) => {

            // 页面加载完成后执行登录逻辑
            win.webContents.executeJavaScript(`
                        window.process=undefined;
                `, true).then((global) => {
                console.log('JavaScript executed successfully');
            }).catch((error) => {
                console.error('JavaScript execution failed:', error);
            });
        })


        // 平博自动登录逻辑
        if (MUtils.isNotEmpty(ConfigContext.globConfig.pbUserName) && MUtils.isNotEmpty(ConfigContext.globConfig.pbPassWord)) {
            win.webContents.on('did-finish-load', () => {
                // 页面加载完成后执行登录逻辑
                win.webContents.executeJavaScript(`
                        const timer = setInterval(function() {
                            const loginId = document.querySelector('input[id="loginId"]');
                            if (loginId != null) {
                                clearInterval(timer);
                                console.log('设置账号密码');
                                document.querySelector('input[id="loginId"]').value = "${ConfigContext.globConfig.pbUserName}";
                                document.querySelector('input[id="pass"]').value = "${ConfigContext.globConfig.pbPassWord}";
                                setTimeout(function() {
                                    const submitButton = document.querySelector('.LoginComponent .form-inline button[type="submit"]');
                                    if (submitButton) {
                                        submitButton.click();
                                    } else {
                                        console.error('Form element not found');
                                    }
                                }, 500);
                            }
                        }, 1000);
                `, true).then((global) => {
                    console.log('JavaScript executed successfully');
                }).catch((error) => {
                    console.error('JavaScript execution failed:', error);
                });
            });
        }
        PbContext.pbWin = win;
        return PbContext.pbWinId;
    }


    async createPbWebWin() {
        chromium.launch({
            headless: false,
            args: [
                '--disable-blink-features=AutomationControlled',
                '--disable-infobars',
                '--start-maximized'
            ]
        }).then(async browser => {
            const context = await browser.newContext();
            const page = await context.newPage();
            await page.evaluate(() => {
                Object.defineProperty(navigator, 'webdriver', {get: () => undefined});
            })

            await page.on('request', (request) => {
            })


            await page.on('response', (response) => {
                let url = response.url();
                if (url.includes("https://www.part987.com/member-service/v2/account-balance")) {
                    response.json().then(response => {
                        Log.info('用户信息接口 response:', response)
                    })

                }
                if (url.includes("https://www.part987.com/sports-service/sv/compact/events?btg=1&c=&cl=3&d=&ec=&ev=&g=QQ%3D%3D&hle=false&ic=false&inl=false&l=3&lang=&lg=&lv=&me=0&mk=2&more=false&o=1&ot=2&pa=0&pimo=0%2C1%2C8%2C39%2C2%2C3%2C6%2C7%2C4%2C5&pn=-1&pv=1&sp=29")) {
                    response.json().then(response => {
                        Log.info('足球滚球列表接口 response:', response)
                    })
                }
            })

            await page.goto('https://www.part987.com/zh-cn/');
            await page.getByPlaceholder('用户名').click();
            await page.getByPlaceholder('用户名').click();
            await this.typeWithDelay(page, '#loginId', ConfigContext.globConfig.pbUserName)
            await this.typeWithDelay(page, '#pass', ConfigContext.globConfig.pbPassWord)
            await page.getByRole('button', {name: '登录'}).click();
        })
    }

    async typeWithDelay(page, selector, text, delay = 100) {
        // 遍历文本中的每一个字符
        for (let char of text) {
            await page.type(selector, char); // 输入单个字符
            await page.waitForTimeout(delay); // 等待指定的延迟时间（毫秒）
        }
    }

    async getPbAccount() {
        let resp = await Services.get("pb").getAccount();
        if (resp != null && resp['loginId'] != null) {
            return new AccountResp(resp['loginId'], resp['loginId'], resp['betCredit']);
        }
        return null;
    }

    async getPbGameList() {
        return await Services.get("pb").getGameList()
    }


    async getPbRecentGameList() {
        return await Services.get("pb").getRecentGameList()
    }

}

/**
 * 解析主机地址
 *
 * @param url
 * @returns {string}
 */
function getHost(url) {
    const parsedUrl = new URL(url);
    return parsedUrl.hostname;
}

PbController.toString = () => '[class PbController]';
module.exports = PbController;